﻿/* 
 Copyright (C) 2011  Amblox Project

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.IO;

using Amblox.Database;
using Amblox.Net;

namespace Amblox
{
    class Environment
    {
        public static Dictionary<string, string> Config;
        public static DatabaseManager dbManager;

        public static int SQLRevision = 2;

        public static int Revision
        {
            get
            {
                return 2;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                Log.Title = "Amblox Project - Rev. " + Revision;

                ReadConfig();

                if (!Config.ContainsKey("Net.GamePort") || !Config.ContainsKey("Database.Host") || !Config.ContainsKey("Database.Port") || !Config.ContainsKey("Database.Name") || !Config.ContainsKey("Database.User") || !Config.ContainsKey("Database.Password"))
                {
                    Log.WriteError("Error loading Config Data at file \"Config.ini\"");
                    Log.WriteError("Press any key for exit.");
                    Console.ReadKey(true);
                    System.Environment.Exit(0);
                }

                string DB_Host = Config["Database.Host"];
                uint DB_Port = Convert.ToUInt32(Config["Database.Port"]);
                string DB_User = Config["Database.User"];
                string DB_Password = Config["Database.Password"];
                string DB_Name = Config["Database.Name"]; 

                dbManager = new DatabaseManager(new DatabaseServer(DB_Host, DB_Port, DB_User, DB_Password), new Database.Database(DB_Name, 10, 1000));

                bool Exit = false;

                using (DatabaseClient dbClient = dbManager.GetClient())
                {
                    dbClient.ExecuteQuery("UPDATE system SET server_status = '1'");

                    int SQL_Current = dbClient.ReadInt("SELECT sql_revision FROM system LIMIT 1");
                    
                    if (SQL_Current != SQLRevision)
                    {
                        Log.WriteError("Error! Check MySQL Database Revision.");
                        dbClient.ExecuteQuery("UPDATE system SET server_status = '0'");
                        Log.WriteError("Press any key for exit.");
                        Exit = true;
                    }
                }

                if (Exit)
                {
                    Console.ReadKey(true);
                    System.Environment.Exit(0);
                }

                NetListener.Init(Convert.ToInt32(Config["Net.GamePort"]));

                Log.WriteLine("Database connection started successfully.");
                Log.WriteLine("Listener started on port: " + Config["Net.GamePort"]);
                Log.WriteLine("Amblox Project started successfully.");
            }
            catch(Exception e)
            {
                Log.WriteError("Unhandled error on loading Amblox Project: " + e.Message);
                Log.WriteError("Press any key for exit.");
                Console.ReadKey(true);
                System.Environment.Exit(0);
            }

            while (true)
                Console.ReadKey(true);
        }

        static void ReadConfig()
        {
            try
            {
                Config = new Dictionary<string, string>();

                StreamReader tr = new StreamReader("Config.ini");
                string A;

                while ((A = tr.ReadLine()) != null)
                {
                    try
                    {
                        if (A.Length < 1)
                            continue;

                        if (A.Substring(0, 1) == "#")
                            continue;
                            
                        string[] FileLine = A.Split('=');
                        
                        string Key = FileLine[0];
                        string Value = FileLine[1];
                        string OldValue = Value;
                            
                        try{
                            Value = Value.Split('#')[0];
                        }catch{
                            Value = OldValue;
                        }

                        Config.Add(Key, Value);
                    }
                    catch
                    {
                        continue;
                    }
                }

                tr.Close();
            }
            catch (Exception e)
            {
                Log.WriteError("Unhandled error loading config: " + e.Message);
                Log.WriteError("Press any key for exit.");
                Console.ReadKey(true);
                System.Environment.Exit(0);
            }
        }
    }
}
